package com.sumer.psychology.space.domain;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;

import java.util.Collection;

/**
 * message溯源对象
 * <p/>
 * Created by twer on 15/4/16.
 */
public class FriendMessage extends BasicDBObject {
    public static BasicDBList classifyByMessageId(BasicDBList allMessages) {
        MultiMap groupByMessageId = new MultiValueMap();
        for (Object message : allMessages) {
            String messageId = (String) ((DBObject) message).get("messageId");
            groupByMessageId.put(messageId, message);
        }

        BasicDBList results = new BasicDBList();
        for (Object key : groupByMessageId.keySet()) {
            Collection messages = (Collection) groupByMessageId.get(key);
            results.add(new FriendMessage(messages));
        }
        return results;
    }

    public FriendMessage(Collection messages) {
        for (Object message : messages) {
            apply((DBObject) message);
        }
    }

    private void apply(DBObject message) {
        // TODO message ids are not same
        put("messageId", message.get("messageId"));
        put("friendMessageType", message.get("friendMessageType"));
        put("ownerIsAcceptor", message.get("ownerIsAcceptor"));
        put("requester", message.get("requester"));
        put("acceptor", message.get("acceptor"));

        if (message.get("requestWords") != null) {
            put("requestWords", message.get("requestWords"));
        }
    }
}
